//
//  YZVideoPlayer.m
//  VET
//
//  Created by YZ on 2018/7/13.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZVideoPlayer.h"
#import <AVFoundation/AVFoundation.h>

@interface YZVideoPlayer()

//播放器对象
@property (nonatomic, strong) AVPlayer *player;

//播放器预览层
@property (nonatomic, strong) AVPlayerLayer *playerLayer;

@end

@implementation YZVideoPlayer

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(runLoopTheMovie:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self stopPlayer];
    self.player = nil;
}

- (void)startPlayer
{
    if (!self.player.rate) {
        [self.player play];
    }
}

- (void)stopPlayer
{
    if (self.player.rate == 1) {
        [self.player pause];//如果在播放状态就停止
    }
}

- (AVPlayerItem *)getAVPlayerItem
{
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:self.videoUrl];
    return playerItem;
}

- (void)runLoopTheMovie:(NSNotification *)noti
{
    //注册的通知  可以自动把 AVPlayerItem 对象传过来，只要接收一下就OK
    AVPlayerItem * pItem = [noti object];
    //关键代码
    [pItem seekToTime:kCMTimeZero];
    [self.player play];
}

#pragma mark -- setters && getters

- (void)setVideoUrl:(NSURL *)videoUrl
{
    _videoUrl = videoUrl;
    self.player = [AVPlayer playerWithPlayerItem:[self getAVPlayerItem]];
    if (self.playerLayer) {
        [self.playerLayer removeFromSuperlayer];
    }
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    self.playerLayer.frame = self.bounds;
    [self.layer addSublayer:self.playerLayer];
}

@end
